package cn.xing.managementSystem.bean.pageable;

import cn.xing.managementSystem.utils.Preconditions;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cuixing
 * @package io.merculet.management.common.bean.pageable
 * @class PageableConverter
 * @email xing.cui@magicwindow.cn
 * @date 2018/4/3 下午4:11
 * @description
 */
public class PageableConverter {
    public static PageRequest toPageRequest(PageableRequest pageableRequest) {
        Sort sort = null;
        if (Preconditions.isNotBlank(pageableRequest.getSortFields())) {
            List<Sort.Order> orders = new ArrayList<>();
            for (SortField sf : pageableRequest.getSortFields()) {
                Sort.Direction direction = sf.getDirection() == SortDirection.ASC ? Sort.Direction.ASC : Sort.Direction.DESC;
                Sort.Order order = new Sort.Order(direction, sf.getFieldName());
                orders.add(order);
            }
            sort = new Sort(orders);
        }else{
            List<Sort.Order> orders = new ArrayList<>();
            Sort.Direction direction = Sort.Direction.DESC;
            Sort.Order order = new Sort.Order(direction, "dateCreated");
            orders.add(order);
            sort = new Sort(orders);
        }
        return Preconditions.isNotBlank(sort)
                ? new PageRequest(pageableRequest.getPageNumber(), pageableRequest.getPageSize(), sort)
                : new PageRequest(pageableRequest.getPageNumber(), pageableRequest.getPageSize());
    }
}